# _*_ coding: UTF-8 _*_
# @Time     : 2021/2/24 下午 03:50
# @Author   : Li Jie
# @Site     : http://www.hzdledu.com/
# @File     : thread_test5.py
# @Software : PyCharm

from queue import Queue
from threading import Thread, Lock
import time
import random


# 使用Queue在线程间通信

# 定义一个生产者Producer和一个消费者Consumer，生产者生产5个产品，依次写入队列，消费者依次从队列中取出产品

# 生产者类
class Producer(Thread):
    def __init__(self, name, queue):
        Thread.__init__(self, name=name)
        self.queue = queue

    def run(self) -> None:
        for i in range(5):
            print(f'生产者{self.getName()}将产品{i}加入队列')
            self.queue.put(i)
            time.sleep(random.random())
        print(f'生产者{self.getName()}生产完成...')


class Consumer(Thread):
    def __init__(self, name, queue):
        Thread.__init__(self, name=name)
        self.queue = queue

    def run(self) -> None:
        for i in range(5):
            num = self.queue.get()
            print(f'消费者{self.getName()}将产品{num}从队列取出')
            time.sleep(random.random())
        print(f'消费者{self.getName()}完成...')


def thread_main():
    print('-----主线程开始------')
    queue = Queue()  # 实例化队列
    producer_thread = Producer('Producer', queue)  # 实例化Producer线程，将队列作为参数传入
    consumer_thread = Consumer('Consumer', queue)  # 实例化Consumer线程，将队列作为参数传入
    producer_thread.start()  # 启动线程producer
    consumer_thread.start()  # 启动线程consumer
    producer_thread.join()  # 等待线程producer结束
    consumer_thread.join()  # 等待线程consumer结束
    print('-----主线程结束------')


if __name__ == '__main__':
    thread_main()
